/**
 * Create by zhangwei on 2015/05/10
 */
var formidable = require('formidable');
var fs = require('fs');
var express = require('express');
var util = require('util');
var router  = express.Router();

router.get('/', function(req, res){

	res.render('upload', {});
});

router.post('/fileupload', function(req, res){

	var form = new formidable.IncomingForm();

	form.encoding = 'utf-8';
	form.uploadDir = global.config.cache_dir;
	form.allow = global.config.allow_upload_type;

	//when a file has been received, then callbak
	form.on('file', function(name, file){
		var targetDir = global.config.upload_dir;

		if(file.path && file.size > 0 && file.type in form.allow && form.allow[file.type]){
			//when upload complete , move the uploaded file to the upload_dir, then callback
			fs.rename(file.path, targetDir + file.name, function(err){
				if( err ) throw err;

				console.log(targetDir+file.name, ' uploaded');
			});

		}else{

			//if the uploaded file is invalid, then unlink it
			fs.unlinkSync(file.path);
		}

	});

	//when the entire request complete, and all comtained files have finished flushing to th disk
	form.on('end', function(){
		console.log('completed.....');
	});

	//parse the post params
	form.parse(req, function(err, fields, files){

		res.writeHead(200, {'content-type': 'text/plain'});
		res.write('received upload:\n\n');
		res.end(util.inspect({fields: fields, files: files}));
	});
});


module.exports = router;